import 'package:flutter_axrjc/datasource/network/api/UserApi.dart';
import 'package:flutter_axrjc/datasource/network/bean/AssetBean.dart';
import 'package:flutter_axrjc/datasource/network/bean/EventBean.dart';
import 'package:flutter_axrjc/datasource/network/request/exp.dart';
import 'package:flutter_axrjc/main.dart';
import 'package:flutter_axrjc/util/Util.dart';
import 'package:flutter_axrjc/widget/image_picker_dialog.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:image_cropper/image_cropper.dart';

import 'state.dart';

class ProfileLogic extends GetxController {
  final ProfileState state = ProfileState();
  @override
  onInit() {
    super.onInit();
    UserApi.getUser().then((value) {
      print(value?.customerInfo?.toJson());
      state.avatar.value = value?.customerInfo?.avatar ?? '';
      state.gender.value = value?.customerInfo?.sex ?? '';
      state.nickname.value = value?.customerInfo?.nickName ?? '';
      state.address.value = value?.customerInfo?.customerAddress ?? '';
      state.birthday.value = value?.customerInfo?.birthday ?? '';
    });
  }

  Future<void> updateAvatar() async {
    AssetBean? a = await showSingleMedia();
    if (a == null) {
      return;
    }
    CroppedFile? file = await ImageCropper().cropImage(
        sourcePath: a.path, aspectRatioPresets: [CropAspectRatioPreset.square]);
    if (file == null) {
      return;
    }

    try {
      state.avatar.value = await UserApi.updateAvatar(file.path);
      EasyLoading.showToast("已上传");
      eventBus.fire(EventBean(type: EventType.refreshProfile, data: null));
    } on ApiException catch (e) {
      EasyLoading.showToast(e.message);
    } catch (e) {
      EasyLoading.showToast("$e");
    }
  }

  Future<void> save() async {
    try {
      await UserApi.updateProfile({
        "birthday": state.birthday.value,
        "nickName": state.nickname.value,
        "customerAddress": state.address.value,
        "sex": state.gender.value,
      });
      var user = await UserApi.getUser();
      user?.customerInfo?.birthday = state.birthday.value;
      user?.customerInfo?.nickName = state.nickname.value;
      user?.customerInfo?.customerAddress = state.address.value;
      user?.customerInfo?.sex = state.gender.value;
      await Util.saveUser(user);
      EasyLoading.showToast("已保存");
      eventBus.fire(EventBean(type: EventType.refreshProfile, data: null));
    } on ApiException catch (e) {
      EasyLoading.showToast(e.message);
    } catch (e) {
      EasyLoading.showToast("$e");
    }
  }
}
